import { Card, Form, Input, Select, Spin } from 'antd';
import React, { useCallback, useContext, useState } from 'react';
import PubSub from 'pubsub-js';
import FlowContext from '@/pages/Flow/FlowContext';
import request from '@/utils/request';
import VersionPageTable from '../../VersionPageTable';

function ValidationPanel({ form, node, update }) {
  const { getFieldDecorator, validateFields } = form;
  const { label, nodeCode, nodeId, messageFormat, nodeVersionId } = node;

  const { state } = useContext(FlowContext);
  const { processId, versionId } = state;
  const [loading, setLoading] = useState(false);
  const isEdit = !!nodeId;

  const [readOnly, setReadOnly] = useState(isEdit);

  const onSave = useCallback(() => {
    validateFields((err, values) => {
      if (!err) {
        setLoading(true);
        if (isEdit) {
          request
            .post(`/validation/updateValidation`, {
              data: { ...values, validationId: nodeId },
            })
            .then(() => {
              update({
                label: values.validationName,
                nodeCode: values.validationCode,
                messageFormat: values.messageFormat,
              });
              setReadOnly(true);
              PubSub.publish(`nodeSave_${processId}_${versionId}`);
            })
            .finally(() => {
              setLoading(false);
            });
        } else {
          request
            .post(`/validation/createValidation`, {
              data: { ...values, processId },
            })
            .then(({ validationId }) => {
              update({
                nodeId: validationId,
                label: values.validationName,
                nodeCode: values.validationCode,
                messageFormat: values.messageFormat,
              });
              setReadOnly(true);
              PubSub.publish(`nodeSave_${processId}_${versionId}`);
            })
            .finally(() => {
              setLoading(false);
            });
        }
      }
    });
  }, [isEdit, nodeId, processId, update, validateFields, versionId]);

  return (
    <Card
      type="inner"
      size="small"
      title="校验器"
      bordered={false}
      extra={
        readOnly ? <a onClick={() => setReadOnly(false)}>编辑</a> : <a onClick={onSave}>保存</a>
      }
    >
      <Spin spinning={loading}>
        <Form>
          <Form.Item label="校验器名称">
            {getFieldDecorator('validationName', {
              initialValue: label,
              rules: [
                {
                  required: true,
                  message: '校验器名称不能为空',
                },
              ],
            })(<Input disabled={readOnly} placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="校验器编码">
            {getFieldDecorator('validationCode', {
              initialValue: nodeCode,
              rules: [
                {
                  required: true,
                  message: '校验器编码不能为空',
                },
              ],
            })(<Input disabled={readOnly} placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="报文格式">
            {getFieldDecorator('messageFormat', {
              initialValue: messageFormat,
              rules: [
                {
                  required: true,
                  message: '报文格式不能为空',
                },
              ],
            })(
              <Select disabled={readOnly || isEdit}>
                <Select.Option value="JSON">JSON</Select.Option>
                <Select.Option value="XML">XML</Select.Option>
              </Select>
            )}
          </Form.Item>
        </Form>
        {isEdit ? (
          <VersionPageTable
            style={{ marginTop: '16px' }}
            element="validation"
            elementIdKey="validationId"
            elementId={nodeId}
            elementVersionId={nodeVersionId}
            routePrefix="validator"
            readOnly={state.readOnly}
            onValidVersion={nodeVersionId => {
              update({ nodeVersionId });
              PubSub.publish(`nodeSave_${processId}_${versionId}`);
            }}
          />
        ) : null}
      </Spin>
    </Card>
  );
}

export default Form.create()(ValidationPanel);
